package com.bjnet.castdemo.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjnet.castdemo.CastManager;
import com.bjnet.castdemo.R;
import com.bjnet.castdemo.ScreenRenderService;
import com.bjnet.castdemo.base.DeviceName;
import com.bjnet.castdemo.util.ViewHelper;

import org.greenrobot.eventbus.EventBus;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class LoginActivity extends FragmentActivity {

    public static final String TAG = "ScreenRender";

    private NetworkReceiver receiver = new NetworkReceiver();
    private static final String ETHNAME = "eth0";

    private View mBar;
    private View mLoadingView;
    private TextView device;
    private TextView ip;
    TextView pinCode;
    ImageView settings;
    private int mShortAnimationDuration;
    private int deviceNumber;
    ConstraintLayout bigP;
    DeviceName deviceName;
    private SharedPreferences sharedPreferences;

    private static boolean wifiConnected = false;
    private static boolean mobileConnected = false;
    private static boolean ethernetConnected = false;

    LinearLayout linearLayout;
    ViewHelper viewHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkReceiver();
        this.registerReceiver(receiver, filter);
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        sharedPreferences = getSharedPreferences(getResources().getString(R.string.device), Context.MODE_PRIVATE);

        bigP = findViewById(R.id.big_p);
        mBar = findViewById(R.id.info_bar);
        mLoadingView = findViewById(R.id.loading);
        device = findViewById(R.id.device);
        ip = findViewById(R.id.ip);
        settings = findViewById(R.id.setting);
        pinCode = findViewById(R.id.pincode);

        linearLayout = findViewById(R.id.parent);
        viewHelper = new ViewHelper(this, linearLayout);
        deviceName = new DeviceName(getApplicationContext());
        deviceNumber = deviceName.getNumber();
        startRenderService();
        firstRunCheck(); //APP第一次运行时检查
    }

    private void startRenderService() {
        Intent startSvc = new Intent(this, ScreenRenderService.class);
        this.startService(startSvc);
    }

    private void firstRunCheck() {
        if (CastManager.getMgr().isFirstUpgrade()) {
            CastManager.getMgr().setFirstUpgrade(false);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        View decoeView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decoeView.setSystemUiVisibility((uiOptions));
        Resources resources = getResources();

        if (CastManager.getMgr().isEnablePin()) {
            refreshPin();
        } else {
            pinCode.setText(getString(R.string.no_pincode));
        }

        mBar.setVisibility(View.GONE);

        if (deviceName.getDeviceName() != null) {
            device.setText(deviceName.getDeviceName());
        } else {
            device.setText("BJ62_" + String.valueOf(deviceNumber));
        }
        checkNetworkConnection();

        mShortAnimationDuration = 3000;

        mBar.setAlpha(0f);
        mBar.setVisibility(View.VISIBLE);

        mBar.animate()
                .alpha(1f)
                .setDuration(mShortAnimationDuration)
                .setListener(null);

    }

    public void settings(View v) {

        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    private void checkNetworkConnection() {
        // BEGIN_INCLUDE(connect)
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()) {
            Log.i(TAG, "checkNetworkConnection: activeInfo type:" + activeInfo.getType());
            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            ethernetConnected = activeInfo.getType() == ConnectivityManager.TYPE_ETHERNET;
            if (wifiConnected) {
                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                Log.i(TAG, "checkNetworkConnection: wifiInfo:" + wifiInfo);
                if (wifiInfo.getIpAddress() == 0) {
                    NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
                    if (NetworkInfo.State.CONNECTED == networkInfo.getState()) {
                        ip.setText(getLocalIp());
                    }
                } else {
                    String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
                    ip.setText(ipAddress);
                }
                //Log.i(TAG, getString(R.string.wifi_connection));
            } else if (ethernetConnected) {
                ip.setText(getLocalIp());
            }
        } else {
            Log.e(TAG, "checkNetworkConnection: no activeInfo");
            ip.setText(getString(R.string.no_network));
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Intent startSvc = new Intent(this, ScreenRenderService.class);
        this.stopService(startSvc);
        viewHelper.onDestroy();
        Log.i(TAG, "MainActivity: onDestroy:");
        if (receiver != null) {
            this.unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    @org.greenrobot.eventbus.Subscribe(threadMode = org.greenrobot.eventbus.ThreadMode.MAIN)
    public void onRefreshPinEvent(com.bjnet.castdemo.event.RefreshPinEvent event) {
        refreshPin();
    }

    private void refreshPin() {

        Log.i(TAG, "refreshPin: pincode:" + CastManager.getMgr().getPincode());

        if (CastManager.getMgr().isEnablePin()) {
            pinCode.setText(CastManager.getMgr().getPincode());
        } else {
            pinCode.setText(getString(R.string.no_pincode));
        }
    }

    private static String getLocalIp() {
        String ip = "0.0.0.0";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address && (intf.getDisplayName().equals(ETHNAME))) {
                        ip = inetAddress.getHostAddress();
                        Log.i(TAG, "getLocalIp: ip:" + ip + " name:" + intf.getDisplayName());
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return ip;
    }

    private static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    public class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkNetworkConnection();
        }
    }

    @Override
    public void onBackPressed() {

        if (viewHelper.hasViews()) {
            viewHelper.clear();
        } else super.onBackPressed();
    }
}
